package com.lenovo.tool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

class AttributesHandler extends DefaultHandler {
    private HashMap<String, AttributesImpl> map = new HashMap<String, AttributesImpl>();
    private ArrayList<String> nameList = new ArrayList<String>();

    private String getKeyName(ArrayList<String> list, Attributes attributes) {
        String[] nodes = new String[attributes.getLength()];

        for (int k = 0; k < nodes.length; k++) {
            String attrName = attributes.getLocalName(k);
            String attrValue = attributes.getValue(k);
            nodes[k] = attrName + "." + attrValue;
        }
        Arrays.sort(nodes);

        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < list.size(); k++) {
            if (k > 0) {
                sb.append(".");
            }
            sb.append(list.get(k));
        }
        for (int k = 0; k < nodes.length; k++) {
            sb.append(".");
            sb.append(nodes[k]);
        }

        return sb.toString();
    }

    public AttributesHandler() {
    }

    public HashMap<String, AttributesImpl> getAttributeMap() {
        return map;
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        nameList.add(qName);

        AttributesImpl imp = new AttributesImpl();
        for (int k = 0; k < attributes.getLength(); k++) {
            String attrName = attributes.getLocalName(k);
            String attrValue = attributes.getValue(k);

            imp.addAttribute("", "", attrName, "", attrValue);
        }

        map.put(getKeyName(nameList, attributes), imp);
    }

    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        nameList.remove(nameList.size() - 1);
    }
}
